﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;

namespace SilverlightPlayer
{
    public class TrackListManager
    {
        WebClient client = new WebClient();

        public TrackListManager()
        {
            Tracks = new ObservableCollection<Track>();
            Uri url = new Uri(App.PlaylistUri, UriKind.RelativeOrAbsolute);
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            
            if(!string.IsNullOrEmpty(App.PlaylistUri) && string.IsNullOrEmpty(App.StreamUri))
                client.OpenReadAsync(url);
        }

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return;
            }
            using (Stream s = e.Result)
            {
                XDocument doc = XDocument.Load(s);
                List<Track> tracks = (from track in doc.Descendants("Track")
                                      select new Track()
                                      {
                                          Location = (string)track.Element("Location"),
                                          Creator = (string)track.Element("Creator"),
                                          Info = (string)track.Element("Info"),
                                          Thumbnail = (string)track.Element("Thumbnail"),
                                          Title = (string)track.Element("Title"),

                                      }).ToList();
                tracks.ForEach(t => Tracks.Add(t));
            }

           

            if (TracksFetched != null) TracksFetched(this, new EventArgs());

        }

        public ObservableCollection<Track> Tracks { get; set; }

        public event EventHandler TracksFetched;
    }
}
